import {
  FC,
  ReactElement,
  useCallback,
  useMemo,
  useRef,
  useState,
} from "react";
import { View as TView } from "@tarojs/components";
import {
  getSetting,
  authorize,
  saveImageToPhotosAlbum,
  getFileSystemManager,
  env,
  showToast,
  setClipboardData,
} from "@tarojs/taro";
import { Button, FlexView, View } from "../BUI";
import { ICode } from "./types";
import Mask from "./Mask";
// eslint-disable-next-line import/first
import { QRCode } from "taro-code";

import "./feedQRCode.css";
import { createCode, previewUrl } from "../../api/feedQRCodeAPI";
import getPx from "../../utils/getPX";

interface IProps {
  code: ICode;
}

const GenerateQRCode: FC<IProps> = ({ code }): ReactElement => {
  const [show, setShow] = useState(false);
  const [loading, setLoading] = useState(false);
  const [id, setId] = useState("");
  const FileSystemManager = useMemo(() => getFileSystemManager(), []);
  const previewURL = useMemo(() => `${previewUrl}${id}`, [id]);
  const codeSize = useMemo(() => getPx(300), []);
  const ContainerHeight = useMemo(() => `${getPx(600)}px`, []);
  const allowGenCode = useMemo(
    () => code.price && code.title && code.imagePath,
    [code]
  );
  const ref = useRef<any>();

  console.log(process.env);
  console.log(process);

  const handlePostCode = useCallback(() => {
    setLoading(true);
    try {
      FileSystemManager.readFile({
        filePath: code.imagePath as string,
        encoding: "base64",
        success: ({ data: imagePath }: any) => {
          console.log("send:", { ...code, imagePath });

          createCode({ ...code, imagePath }).then(({ data }) => {
            console.log("res", data);
            setId(data);
            setLoading(false);
          });
        },
      });
    } catch (error) {
      console.error(error);
      showToast({ title: "出现错误", icon: "none" });
      setShow(false);
    }
  }, [FileSystemManager, code]);

  const handleGenerate = useCallback(() => {
    if (!show) {
      if (allowGenCode) {
        setShow(!show);
        //发送请求
        handlePostCode();
      } else showToast({ title: "不能有空项", icon: "none" });
    } else setShow(!show);
  }, [allowGenCode, handlePostCode, show]);

  const handleWriteFile = useCallback(() => {
    const base64 = ref.current.childNodes[0].props.src;
    const data = base64.split(",")[1];
    const filePath = `${env.USER_DATA_PATH}/${id}.png`;

    FileSystemManager.writeFile({
      data,
      filePath,
      encoding: "base64",
      success: (res) => {
        console.log(res);
        saveImageToPhotosAlbum({
          filePath,
          success: () => {
            console.log("👏");
          },
        });
      },
      fail: (err) => {
        console.error(err);
      },
    });
  }, [FileSystemManager, id]);

  const handleSaveCode = useCallback(() => {
    getSetting({
      success: function ({ authSetting }) {
        //没有权限则申请
        if (!authSetting["scope.writePhotosAlbum"]) {
          authorize({
            scope: "scope.writePhotosAlbum",
            success: () => {
              //存储二维码
              handleWriteFile();
            },
          });
        } else handleWriteFile();
      },
    });
  }, [handleWriteFile]);

  const handleCopyPreViewURL = useCallback(() => {
    setClipboardData({
      data: previewURL,
      success: function () {
        showToast({ title: `前往浏览器打开`, icon: "none" });
      },
    });
  }, [previewURL]);
  //! 待解决 元素 image 的 属性 src 的值数据量过大，可能会影响渲染性能。考虑降低图片转为 base64 的阈值或在 CSS 中使用 base64
  const MemoQRCode = useMemo(
    () =>
      allowGenCode ? (
        <TView ref={ref}>
          <QRCode
            text={previewURL}
            size={codeSize}
            scale={2}
            errorCorrectLevel='M'
            typeNumber={2}
          />
        </TView>
      ) : null,
    [allowGenCode, codeSize, previewURL]
  );

  return (
    <View
      className='container'
      style={{
        top: `calc(100% - ${show ? ContainerHeight : "46px"})`,
        height: ContainerHeight,
      }}
    >
      <Button
        width='100%'
        onClick={handleGenerate}
        letterSpacing='2px'
        radius='0'
      >
        生成二维码
      </Button>
      <FlexView
        column
        width='100%'
        alignItems='center'
        justifyContent='space-evenly'
        style={{
          filter: loading ? "blur(10rpx)" : undefined,
          flex: 1,
        }}
      >
        {MemoQRCode}
        <FlexView width='100%'>
          <Button onClick={handleSaveCode}>保存本地</Button>
          <Button onClick={handleCopyPreViewURL}>复制查看地址</Button>
        </FlexView>
      </FlexView>
      <Mask state={loading} ContainerHeight={ContainerHeight} />
    </View>
  );
};

export default GenerateQRCode;
